package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author 陈辉
 * @data 2023 11:27
 */
@Service
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    @Override
    public long addTask(TaskDto task) {
        //1. 将任务添加到数据库
        boolean res = addTaskToDB(task);

        if (res) {
            //2. 将符合条件的任务添加到redis缓存
            addTaskToRedis(task);
        }

        return task.getTaskId();
    }

    /**
     * 拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public TaskDto poll(Integer type, Integer priority) {
        //1. 从redis的list中弹出一个任务并返回
        String key = ScheduleConstants.TOPIC + type + "_" + priority;
        String taskJSON = cacheService.lRightPop(key);
        if (StringUtils.isNotEmpty(taskJSON)) {
            TaskDto taskDto = JSON.parseObject(taskJSON, TaskDto.class);

            //2. 删除数据库表：taskInfo中对应的任务
            taskinfoMapper.deleteById(taskDto.getTaskId());

            //3. 修改taskInfoLogs表中的任务状态
            TaskinfoLogs taskinfoLog = taskinfoLogsMapper.selectById(taskDto.getTaskId());
            taskinfoLog.setStatus(1);
            taskinfoLogsMapper.updateById(taskinfoLog);
            return taskDto;
        } else {
            return null;
        }
    }

    /**
     * 将任务添加到缓存
     *
     * @param task
     */
    private void addTaskToRedis(TaskDto task) {
        long executeTime = task.getExecuteTime();
        String key = task.getTaskType() + "_" + task.getPriority();         // topic_1001_1

        //1. 将执行时间 <= 当前系统时间的任务存入redis  list中
        if (executeTime <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (executeTime <= System.currentTimeMillis() + (1000 * 60 * 5)) {
            //2. 任务执行时间 <= 当前系统时间+ 5分钟，将任务存入redis  zset中
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 将任务添加到数据库
     *
     * @param taskDto
     * @return
     */
    private boolean addTaskToDB(TaskDto taskDto) {
        try {
            //1. 将dto数据 复制到实体类对象中
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(taskDto, taskinfo);
            taskinfo.setExecuteTime(new Date(taskDto.getExecuteTime()));

            //2. 先保存任务：将任务数据先存入taskInfo
            taskinfoMapper.insert(taskinfo);

            taskDto.setTaskId(taskinfo.getTaskId());

            //3. 再保存任务日志：将任务数据存入taskInfoLogs
            TaskinfoLogs logs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, logs);
            logs.setStatus(0);
            logs.setVersion(1);
            taskinfoLogsMapper.insert(logs);
            return true;

        } catch (BeansException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 定时将数据库数据同步到redis中
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void refreshDataFromDBToRedis() {
        //1. 先清空缓存中的任务  list, zset
        clearCache();

        //2. 查询数据库中临近5分钟内要执行的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        Date date = calendar.getTime();
        //Date date = new Date(System.currentTimeMillis() + (1000 * 60 * 5));
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, date));

        //3. 将查到的任务存入redis
        if (taskinfos != null && taskinfos.size() > 0){
            for (Taskinfo taskinfo : taskinfos) {
                TaskDto dto = new TaskDto();
                BeanUtils.copyProperties(taskinfo,dto);
                addTaskToRedis(dto);
            }
        }

    }

    //清空redis缓存中的任务
    private void clearCache() {
        String topicPattern = ScheduleConstants.TOPIC + "*";
        String futurePattern = ScheduleConstants.FUTURE + "*";

        Set<String> topicKeys = cacheService.scan(topicPattern);
        Set<String> futureKeys = cacheService.scan(futurePattern);

        if (topicKeys != null && topicKeys.size() > 0) {
            cacheService.delete(topicKeys);
        }
        if (futureKeys != null && futureKeys.size() > 0) {
            cacheService.delete(futureKeys);
        }
    }


    /**
     * 定时刷新redis中的ZSet数据到List中
     * 频次： 每分钟一次
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        //分布式锁控制
        String lock = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if (lock != null) {
            //1. 拿到所有未来数据对应的key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");   //[future_1001_1]

            if (futureKeys != null && futureKeys.size() > 0) {
                //2. 遍历所有future key
                for (String futureKey : futureKeys) {
                    //futureKey: future_1001_1
                    String[] split = futureKey.split(ScheduleConstants.FUTURE);         //["","1001_1"]
                    String topicKey = ScheduleConstants.TOPIC + split[1];                 // topicKey: topic_1001_1

                    //取出ZSet中当前已经到期的任务数据
                    Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                    //将到期的任务由ZSet刷新到list中
                    if (!tasks.isEmpty()) {
                        //将这些任务数据添加到消费者队列中
                        cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                        System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                    }
                }
            }
        }

    }
}
